//    Copyright (C) 2013  <lugocreation@gmail.com>
//
//    This program is free software: you can redistribute it and/or modify
//    it under the terms of the GNU General Public License as published by
//    the Free Software Foundation, either version 3 of the License, or
//    (at your option) any later version.
//
//    This program is distributed in the hope that it will be useful,
//    but WITHOUT ANY WARRANTY; without even the implied warranty of
//    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//    GNU General Public License for more details.
//
//    You should have received a copy of the GNU General Public License
//    along with this program.  If not, see <http://www.gnu.org/licenses/>
package org.jpgolay.wi.realestate;

import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.print.PrinterJob;
import java.beans.PropertyVetoException;
import java.util.Vector;
import javax.swing.*;
import javax.swing.event.InternalFrameEvent;
import javax.swing.event.InternalFrameListener;
import org.jpgolay.gui.iconBar.*;
import org.jpgolay.gui.progressBar.ProgressBar;
import org.jpgolay.gui.progressBar.SwingWorker;
import org.jpgolay.wi.list.ListPrint;
import org.jpgolay.wi.user.User;
import org.jpgolay.wi.util.BrowserControl;
import org.jpgolay.wi.util.WIDate;

// Referenced classes of package org.jpgolay.wi.realestate:
//            RealEstateList, RealEstateCRUD, RealEstateListGUI, RealEstateController
public class RealEstateListController {

    public RealEstateListController(String realEstateId) {
        this.realEstateId = "";
        id = "";
        this.realEstateId = realEstateId;
        initComponent();
        date = new WIDate();
    }

    private boolean initComponent() {
        if (reList == null) {
            reList = new RealEstateList(1);
            crud = new RealEstateCRUD();
        }
        if (relGui == null || relGui.isClosed()) {
            relGui = new RealEstateListGUI();
            relGui.setIconifiable(true);
            relGui.setResizable(false);
            relGui.setMaximizable(false);
            relGui.setClosable(true);
            relGui.setVisible(true);
            relGui.toFront();
            relGui.getSearchB().addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent evt) {
                    search();
                }
            });
            relGui.getSaveMI().addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent evt) {
                    getActionPanel();
                }
            });
            relGui.getSelectF().addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent evt) {
                    search();
                }
            });
            relGui.getHelpMI().addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent evt) {
                    actionHelp();
                }
            });
            relGui.getPrintMI().addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent evt) {
                    PrinterJob pj = PrinterJob.getPrinterJob();
                    if (pj.printDialog()) {
                        actionPrint();
                    }
                }
            });
            relGui.getIconBar().addAnswerListener(new AnswerListener() {
                public void create(AnswerEvent answerevent) {
                }

                public void open(AnswerEvent answerevent) {
                }

                public void modify(AnswerEvent answerevent) {
                }

                public void save(AnswerEvent e) {
                    getActionPanel();
                }

                public void remove(AnswerEvent answerevent) {
                }

                public void print(AnswerEvent e) {
                    actionPrint();
                }

                public void help(AnswerEvent e) {
                    actionHelp();
                }
            });
            relGui.addInternalFrameListener(new InternalFrameListener() {
                public void internalFrameActivated(InternalFrameEvent arg0) {
                    relGui.getSearchB().requestFocusInWindow();
                }

                public void internalFrameClosed(InternalFrameEvent internalframeevent) {
                }

                public void internalFrameClosing(InternalFrameEvent internalframeevent) {
                }

                public void internalFrameDeactivated(InternalFrameEvent internalframeevent) {
                }

                public void internalFrameDeiconified(InternalFrameEvent internalframeevent) {
                }

                public void internalFrameIconified(InternalFrameEvent internalframeevent) {
                }

                public void internalFrameOpened(InternalFrameEvent internalframeevent) {
                }
            });
            return true;
        }
        if (relGui.isIcon()) {
            try {
                relGui.setIcon(false);
            } catch (PropertyVetoException e) {
                e.printStackTrace();
            }
        }
        relGui.setVisible(true);
        relGui.toFront();
        return false;
    }

    private void search() {
        SwingWorker worker = new SwingWorker() {
            public Object construct() {
                boolean next = true;
                reList.setCategory(relGui.getCategorie());
                reList.setSort(relGui.getGenre());
                reList.setType(relGui.getType());
                reList.setMeuble(relGui.getMeuble());
                if (!relGui.getSelect().equals("") && !relGui.getSelect().equals(" ")) {
                    if (relGui.getSelectType() == 0) {
                        reList.setFiche(relGui.getSelect());
                        reList.setLot("indiff\351rent");
                        reList.setReference("indiff\351rent");
                        reList.setResidence("indiff\351rent");
                    } else if (relGui.getSelectType() == 1) {
                        reList.setLot(relGui.getSelect());
                        reList.setFiche("indiff\351rent");
                        reList.setReference("indiff\351rent");
                        reList.setResidence("indiff\351rent");
                    } else if (relGui.getSelectType() == 2) {
                        reList.setReference(relGui.getSelect());
                        reList.setFiche("indiff\351rent");
                        reList.setLot("indiff\351rent");
                        reList.setResidence("indiff\351rent");
                    } else if (relGui.getSelectType() == 3) {
                        reList.setResidence(relGui.getSelect());
                        reList.setReference("indiff\351rent");
                        reList.setFiche("indiff\351rent");
                        reList.setLot("indiff\351rent");
                    }
                } else {
                    reList.setFiche("indiff\351rent");
                    reList.setLot("indiff\351rent");
                    reList.setReference("indiff\351rent");
                    reList.setResidence("indiff\351rent");
                }
                reList.setPrice(relGui.getPrix());
                reList.setAvailability(relGui.getDisponibilite());
                if (!relGui.getDisponibilite().equals("indiff\351rente")) {
                    if (date.isValid(relGui.getDateDu()) && date.isValid(relGui.getDateAu())) {
                        reList.setDateDu(date.toDB(relGui.getDateDu()));
                        reList.setDateAu(date.toDB(relGui.getDateAu()));
                    } else {
                        next = false;
                        JOptionPane.showMessageDialog(relGui, "WIDate invalid !");
                    }
                }
                if (next) {
                    startProgressBar();
                    reList.setReserve(relGui.getReserve());
                    reList.setOption(relGui.getOption());
                    reList.setSector(relGui.getSecteur());
                    reList.setWeb(relGui.getVisibilite());
                    reList.setArchive(relGui.getArchive());
                    reList.setParking(relGui.getParking());
                    reList.setGarage(relGui.getGarage());
                    reList.setKitchen(relGui.getCuisine());
                    reList.setGarden(relGui.getJardin());
                    reList.setPool(relGui.getPiscine());
                    reList.setStanding(relGui.getStanding());
                    reList.setOrderBy(relGui.getOrderBy());
                    if (reList.searchBy(realEstateId)) {
                        relGui.setRangees(reList.getRows());
                        relGui.setColonnes(reList.getColumns());
                        relGui.refreshTable();
                        stopProgressBar();
                    } else {
                        stopProgressBar();
                        JOptionPane.showMessageDialog(relGui, "Aucune donn\351e ne correspond \340 la recherche !");
                    }
                }
                return null;
            }
        };
        worker.start();
    }

    private void actionPrint() {
        String columnName[] = {
            "col1", "col2", "col3", "col4", "col5", "col6", "col7", "col8", "col9"
        };
        Object data[][] = new Object[relGui.getRangees().size() / relGui.getColonnes().size()][9];
        int j = 0;
        int delta = relGui.getColonnes().size() - 9;
        for (int i = 0; i < data.length; i++) {
            data[i][0] = (String) relGui.getRangees().get(j++);
            data[i][1] = (String) relGui.getRangees().get(j++);
            data[i][2] = (String) relGui.getRangees().get(j++);
            data[i][3] = (String) relGui.getRangees().get(j++);
            data[i][4] = (String) relGui.getRangees().get(j++);
            data[i][5] = (String) relGui.getRangees().get(j++);
            data[i][6] = (String) relGui.getRangees().get(j++);
            data[i][7] = (String) relGui.getRangees().get(j++);
            data[i][8] = (String) relGui.getRangees().get(4 + j++);
            j = delta + j;
        }

        ListPrint listPrint = new ListPrint(data, columnName, "realestateList", false);
    }

    private void actionHelp() {
        BrowserControl.displayURL("www.ifacile.com");
    }

    public void setActionPanel(String id) {
        final String ID = id;
        SwingWorker worker = new SwingWorker() {
            public Object construct() {
                startProgressBar();
                if (crud.findByPrimaryKey(ID)) {
                    relGui.setActionArchive(crud.getArchive());
                    relGui.setVisibility(crud.getVisibilite());
                    relGui.setInfosL(ID);
                    stopProgressBar();
                } else {
                    stopProgressBar();
                }
                return null;
            }
        };
        worker.start();
    }

    private void getActionPanel() {
        SwingWorker worker = new SwingWorker() {
            public Object construct() {
                startProgressBar();
                crud.setArchive(relGui.getActionArchive());
                crud.setVisibilite(relGui.getVisibility());
                if (crud.modify()) {
                    stopProgressBar();
                    JOptionPane.showMessageDialog(relGui, "Op\351ration ex\351cut\351e avec succ\350s !");
                } else {
                    stopProgressBar();
                    JOptionPane.showMessageDialog(relGui, "Op\351ration a \351chou\351e !\nUn autre utilisateur a peut-\352tre modifi\351 cette fiche entre temps.");
                }
                relGui.setInfosL("");
                return null;
            }
        };
        worker.start();
    }

    public boolean init() {
        if (relGui == null || relGui.isClosed()) {
            boolean result = initComponent();
            if (result) {
                setLaw(usr);
            }
            return result;
        }
        search();
        if (relGui.isIcon()) {
            try {
                relGui.setIcon(false);
            } catch (PropertyVetoException e) {
                e.printStackTrace();
            }
        }
        relGui.setVisible(true);
        relGui.toFront();
        return false;
    }

    public RealEstateListGUI getVREL() {
        return relGui;
    }

    public JTable getTable() {
        return relGui.getResultat();
    }

    public int recherchePanel() {
        return relGui.rechercheTP();
    }

    public void iconified() {
    }

    public void unIconified() {
        if (relGui != null) {
            relGui.setVisible(true);
        }
    }

    public void maximizeFrame() {
        try {
            relGui.setMaximum(true);
        } catch (PropertyVetoException e) {
            e.printStackTrace();
        }
    }

    public void setDefaultMainFrame(JFrame desktop) {
        this.desktop = desktop;
    }

    private void startProgressBar() {
        if (pb == null) {
            pb = new ProgressBar(desktop, false);
            pb.setLocationRelativeTo(relGui);
            relGui.setEnabled(false);
            pb.setVisible(true);
            pb.start();
        } else {
            relGui.setEnabled(false);
            pb.setVisible(true);
            pb.start();
        }
    }

    private void stopProgressBar() {
        if (!pb.isStop()) {
            pb.stop();
            pb.setVisible(false);
            relGui.setEnabled(true);
        }
    }

    private void setLaw(User usr) {
        String b = Long.toBinaryString(usr.getAccess().intValue());
        int position = b.length();
        if ((position -= 4) >= 0 && b.charAt(position) == '1') {
            relGui.law = true;
        }
    }

    public void setUser(User usr) {
        this.usr = usr;
        setLaw(usr);
    }
    private ProgressBar pb;
    private RealEstateListGUI relGui;
    private RealEstateController reCtrl;
    private RealEstateList reList;
    private RealEstateCRUD crud;
    private String realEstateId;
    private Dimension screen;
    private JFrame desktop;
    private WIDate date;
    private User usr;
    private String id;
}
